import {
  queryClassifyList,
  queryClassifyBanner,
  querfinalList,
  addCart,
  deleCart,
  updateCart,
  queryCart,
  synCart,
  getOrderCount,
  queryNewClassifyList,
  queryPromotionInfoOffLine,
  scanDeleteShoppingCart,
} from '../../utils/ReturnAxios';
import {Toast} from '../../utils/toast';
import saveLocal from '@/utils/NoLogSaveCart';
import axios from 'axios';

export default {
  namespaced: true,
  state: {
    cartIcon: null,
    userinfo: null,
    login: true,
    classifyList: null, // 分类信息列表
    newClassifyList: null,
    classifyIndex: 0, // 分类活动编号
    classifyImageList: null, // 分类图片
    cartanimateArray: [], // 购物车动画数组
    cartanimateNumber: 0, // 购物车变化数量
    aftrerDiscountMoney: 0, // 优惠后总金额
    discountMoney: 0, // 优惠金额
    totalWorkingFee: 0,
    obj: {},
    processListData: {}, // 加工信息数据
    canAfterSaleCount: 0, // 可售后数量
    isLoadShowCart: false, //是否在登录后才可以加入购物车
    selectLadderList: [], //阶梯加价增
    selectGiftList: [], // 阶梯赠品
    buyMoreData: [], // 每满加价增
    orderConfig: {type: 'isPutTimeSort', order: ''},
    couponsConfig:{
      isPutTimeSort: 2
    },
    allMoreBuy: null, //当前所有可参加 每满加
    allLadderList: null, // 当前所有可参加的阶梯加赠
    allGiftList: [], // 当前所有 可参加 阶梯送礼活动
    cartAddNum: 1, // 添加动画
    bodyScrollTop: 0, //滚轮高度
    cjyPagePosition: {}, //页面位置
    cartArray: null,
    activeCartList: null,
    offLineAcitveData: [], //在线活动列表
    offLineSelectData: [], //离线线选中列表
    bagList: [], //购物袋列表
    checkedCartList: [], //已选商品项目
    pagePosY: 0, // 页面位置
    returnPos: {},
    isReturn: false,
    pageNum: 1,
  },
  getters: {
    selectGiftList: state => {
      var selectGiftList = state.selectGiftList;
      var allGiftList = state.allGiftList;
      var returnSelectGiftList = selectGiftList.filter((list, index) => {
        return allGiftList.some(item => {
          var isSome = item.goodsCode == list.goodsCode && item.promId == list.promId;
          if (isSome) {
            selectGiftList[index].goodsCodeList = item.goodsCodeList
            list.promCode = item.promCode;
          }
          return isSome;
        });
      });
      return returnSelectGiftList;
    },

    buyMoreData: state => {
      var obj = state.allMoreBuy;
      var selectLadderList = state.buyMoreData;
      var resSelectLadderList = [];
      if (!obj) {
        return resSelectLadderList;
      }
      selectLadderList.map(item => {
        var resgoodsList = obj[item.promId];
        if (resgoodsList) {
          item.goodsList = resgoodsList.goodsList;
          item.promCode = resgoodsList.promCode;
          resSelectLadderList.push(item);
        }
      });
      return resSelectLadderList;
    },

    selectLadderList: state => {
      var obj = state.allLadderList;
      var selectLadderList = state.selectLadderList;

      var resSelectLadderList = [];

      selectLadderList.map(item => {
        var resgoodsList = obj[item.promId];
        if (resgoodsList) {
          item.goodsList = resgoodsList.goodsList;
          item.promCode = resgoodsList.promCode;
          resSelectLadderList.push(item);
        }
      });
      return resSelectLadderList;
    },

    buyMorePrice: (state, getters) => {
      var price = 0;
      var buyMoreData = getters.buyMoreData;
      var allLadderList = getters.selectLadderList;
      if (buyMoreData.length > 0 || allLadderList.length > 0) {
        allLadderList.map(item => {
          var addMoney = item.addMoney || 0;
          price += addMoney;
        });
        buyMoreData.map(item => {
          var addMoney = item.addMoney || 0;
          var selectNum = item.selectNum || 0;
          price += addMoney * selectNum;
        });
      }
      return price;
    },

    totalPrice(state) {
      var allPrice = 0;
      state.checkedCartList.map(item => {
        var commodityPrice = item.addPrice || 0;
        var workingInfo = item.workingInfo ? JSON.parse(item.workingInfo) : {procemoney: 0};
        var procePriceoney = workingInfo.procemoney || 0;
        allPrice += (parseFloat(commodityPrice) + parseFloat(procePriceoney)) * (item.goodsNum || 0);
      });
      return allPrice;
    },

    discountMoney(state) {
      var discountMoney = state.discountMoney;
      return discountMoney;
    },

    totalWorkingFee(state) {
      var totalWorkingFee = state.totalWorkingFee;
      return totalWorkingFee;
    },

    newClassifyData(state) {
      var classifyData = state.newClassifyList;
      if (!classifyData) {
        return null;
      }
      var dataList = [];
      var obj = {};

      classifyData.sort((a, b) => {
        var NoA = a.sortNo || 0
        var NoB = b.sortNo || 0
        if (NoA != NoB) {
          return NoA - NoB
        }
        else {
          return parseInt(a.classCode) - parseInt(b.classCode)
        }

      })
      //找出所有的一级分类
      var newData = classifyData.filter(item => {
        return item.level == '1' && item.status != 0;
      });
      var secLevelList = classifyData.filter(item => {
        return item.level == '2' && item.status != 0;
      });

      var thrLevelList = classifyData.filter(item => {
        return item.level == '3' && item.status != 0;
      })
      //利用一级分类code 找出所有的二级分类
      newData.forEach(function (item) {
        //将一级分类code保存在变量goodsClassCode中
        var goodsClassCode = item.classCode;
        item.goodsClassCode = item.classCode;
        item.goodsClassName = item.className;
        item.goodsClassId = item.classId;
        item.secList = [];
        // 遍历分类列表寻找每一个一级分类下对应的二级分类并保存
        secLevelList.map((ele, index) => {
          if (ele.classParentCode == goodsClassCode) {
            var secCode = ele.classCode
            var thrList = [{
              goodsClassCode: ele.classCode,
              goodsClassId: ele.classId,
              goodsClassName: '全部',
              imgUrl: ele.imageUrl,
              level: ele.level
            }]
            thrLevelList.map(thrItem => {
              if (thrItem.classParentCode == secCode) {
                thrList.push({
                  goodsClassCode: thrItem.classCode,
                  goodsClassId: thrItem.classId,
                  goodsClassName: thrItem.className,
                  imgUrl: thrItem.imageUrl,
                  level: thrItem.level,
                  superScript: thrItem.superscript,
                  superScriptStatus: thrItem.superscriptStatus,
                })
              }
            })

            item.secList.push({
              goodsClassCode: ele.classCode,
              goodsClassId: ele.classId,
              goodsClassName: ele.className,
              imgUrl: ele.imageUrl,
              superScript: ele.superscript,
              superScriptStatus: ele.superscriptStatus,
              thrList,
              level: ele.level
            });
          }
        });
        if (item.secList.length == 0) {
          item.secList = [
            {
              goodsClassCode: item.classCode,
              goodsClassName: item.className,
              goodsClassId: item.classId,
              level: 1,
              thrList: [
                {
                  goodsClassCode: item.classCode,
                  goodsClassId: item.classId,
                  goodsClassName: '全部',
                  imgUrl: item.imageUrl,
                  level: 1
                }
              ]
            }
          ];
        }
        dataList.push(item);
      });
      return dataList;
    },

    //商品分类列表
    classifyData(state) {
      var classifyData = state.classifyList;
      if (!classifyData) {
        return null;
      }
      var dataList = [];
      var obj = {};
      //找出所有的一级分类
      var newData = classifyData.filter(item => {
        return item.level == '1';
      });
      //利用一级分类code 找出所有的二级分类
      newData.forEach(function (item) {
        //将一级分类code保存在变量goodsClassCode中
        var goodsClassCode = item.goodsclasscode;
        item.goodsClassCode = item.goodsclasscode;
        item.goodsClassName = item.goodsclassname;
        item.goodsClassId = item.goodsclassid;
        item.secList = [
          {
            goodsClassId: item.goodsclassid,
            goodsClassCode: item.goodsclasscode,
            goodsClassName: '全部',
            imgUrl: item.imgurl,
          },
        ];
        // 遍历分类列表寻找每一个一级分类下对应的二级分类并保存
        classifyData.map((ele, index) => {
          if (ele.parentclasscode == goodsClassCode) {
            item.secList.push({
              goodsClassCode: ele.goodsclasscode,
              goodsClassId: ele.goodsclassid,
              goodsClassName: ele.goodsclassname,
              imgUrl: ele.imgurl,
            });
          }
        });
        dataList.push(item);
      });
      console.log('dataList', dataList)
      return dataList;
    },

    cartList(state) {
      return state.activeCartList || [];
    },

    offLineAcitveData(state) {
      return state.offLineAcitveData || [];
    },

    offLineSelectData(state) {
      return state.offLineSelectData || [];
    },

    //商品数量
    cartNum(state) {
      var count = 0;
      var activeCartList = state.activeCartList;
      if (state.activeCartList) {
        // var list = state.activeCartList
        // list.map((item) => {
        //   count += item.goodsNum
        // })
        count = activeCartList.length;
        return count;
      }
      return 0;
    },

    cartTotalNum(state) {
      var count = 0;
      var activeCartList = state.activeCartList;
      if (state.activeCartList) {
        var list = state.activeCartList;
        list.map(item => {
          var goodsNum = item.goodsType == 7 ? 1 : item.goodsNum || 0;
          count += goodsNum;
        });
        return count;
      }
      return 0;
    },
  },

  actions: {
    async getOrderCount({commit}) {
      var res = await  getOrderCount()
      res = res.data
      if (!res.returnCode) {
        return
      }
      var orderCount = res.data[0].orderCount
      commit('SET_ORDER_COUNT', orderCount)
    },

    storeCodeOnChange({commit, dispatch}) {
      commit('QUERY_ACTIVE_LIST');
      dispatch('queryNewClassifyList');
    },

    async queryNewClassifyList({commit}, data) {
      // 获取分类数据
      var res = await queryNewClassifyList();
      res = res.data;
      commit('QUERY_NEW_CLASSIFY_LIST', res);
    },

    async queryClassifyList({commit}, data) {
      // 获取分类数据
      var res = await queryClassifyList();
      res = res.data;
      commit('QUERY_CLASSIFY_LIST', res);
    },
    async queryClassifyBanner({commit}, data) {
      // 获取分类banner图

      var res = await querfinalList();
      res = res.data;
      commit('QUERY_CLASSIFY_BANNER', res);
    },
    //合并购物车
    async synCart({dispatch, commit}) {
      var cartArray = localStorage.getItem('cartArray');
      var sessionId = localStorage.getItem('sessionId')
      if (!cartArray || !sessionId) {
        dispatch('queryCart');
        return;
      }
      cartArray = cartArray ? JSON.parse(cartArray) : [];
      var cartList = [];
      for (var list of cartArray) {
        var shoppingCartLists = list.shoppingCartLists;
        var addCartList = shoppingCartLists.map(item => {
          return {
            goodsId: item.goodsId,
            goodsCode: item.goodsCode,
            goodsType: item.goodsType,
            storeCode: item.storeCode,
            goodsNum: item.goodsNum,
            serve: item.serve,
            workingInfo: item.workingInfo,
            goodsDeliveryType: item.goodsDeliveryType,
            addPrice: item.addPrice,
            goodsWeight:item.goodsWeight,
            processingList:item.processingList
          };
        });
        cartList = cartList.concat(addCartList);
      }

      if (cartList.length > 0) {
        var res = await addCart(cartList);
        res = res.data;
        if (res.returnCode == 0) {
          Toast({
            message: res.msg,
            type: 'fail',
          });
          return;
        }
      }

      //准备清本地空购物车吧
      localStorage.setItem('cartArray', '');
      commit('QUERY_CART', res.data);
    },
    //获得购物车数量
    async queryCart({commit, dispatch, state}) {
      commit('CLEAR_CART');
      var sessionId = localStorage.getItem('sessionId');
      sessionId = sessionId == 'undefined' ? '' : sessionId;
      if (!sessionId && !state.isLoadShowCart) {
        dispatch('queryCartFromLocal');
        return;
      }
      var res = await queryCart();
      res = res.data;
      commit('QUERY_CART', res.data);
    },

    async clearOffLineDetail({commit, state}) {
      // var activeList = state.offLineAcitveData
      // console.log(activeList)
      // var ridList = activeList.map((item) => {
      //   return item.rid
      // })
      // if (activeList.length == 0) {
      //   return
      // }
      // ridList = ridList.join(',')
      // var res = await scanDeleteShoppingCart(ridList)
      // res = res.data
      // if (res.returnCode == 0) {
      //   Toast({
      //     message: res.msg,
      //     type: 'fail'
      //   })
      //   return
      // }
      //
      // commit('CLEAR_OFF_LINE_DATA')
      commit('CLEAR_OFF_LINE_DETAIL');
    },
    // 从本地获取购物车相关信息
    queryCartFromLocal({commit}) {
      var cartArray = localStorage.getItem('cartArray');
      cartArray = cartArray ? JSON.parse(cartArray) : [];
      commit('QUERY_CART', cartArray);
    },

    // 添加到购物车
    async addShoppingCart({commit}, config) {
      var res = await addCart(config);
      res = res.data;
      if (res.returnCode == 0) {
        Toast({
          message: res.msg,
          type: 'fail',
        });
        return;
      }

      commit('QUERY_CART', res.data);
    },

    //更新购物车数量
    async updataCart({commit}, config) {

      var res = await updateCart(config);
      res = res.data;
      if (res.returncode == 0 || res.returnCode == 0) {
        Toast({
          message: res.msg,
          type: 'fail',
        });
      }
      commit('UPDATA_CART', res);

    },
    // 从购物车中删除setStoreConfig
    async deleCart({commit}, config) {
      var ids = [];
      config.shoppingCartList.map(item => {
        ids.push(item.rid);
      });
      ids = ids.join(',');
      var res = await deleCart(ids);
      res = res.data;

      if (res.returncode == 0 || res.returnCode == 0) {
        Toast({
          message: res.msg,
          type: 'fail',
        });
      }
      var shoppingCartList = config.shoppingCartList;
      commit('DELE_CART', shoppingCartList);

    },
    //+++++
    changeClassifyIndex({commit}, index) {
      // 更改当前页面的index
      commit('CHANGE_CLASSIFY_INDEX', index);
    },
    //购物车动画
    addCartAnimate({commit}, num) {
      commit('ADD_CART_ANIMATE', num);
    },
  },
  mutations: {
    SET_ORDER_COUNT(state, data) {
      state.canAfterSaleCount = data
    },

    CHANGE_ORDER_CONFIG(state, data) {
      if (data) {
        state.orderConfig = data;
        console.log('23423423');
      } else {
        console.log('come in');
        state.orderConfig = {type: 'isPutTimeSort', order: ''};
      }
    },
    // 凑单过滤查询数据
    CHANGE_COUPONS_CONFIG(state, data) {
      if (data) {
        state.couponsConfig = data;
        console.log('23423423****');
      } else {
        console.log('come in');
        state.couponsConfig = {};
      }
    },
    //清除购物相关数据
    CLEAR_CART(state, data) {
      state.cartArray = null;
    },
    //将分类列表数据添加到classifyIndex
    QUERY_CLASSIFY_LIST(state, res) {
      if (!state.classifyList) {
        state.classifyList = res.data[0];
      }
    },

    //新的分类数据
    QUERY_NEW_CLASSIFY_LIST(state, res) {
      var classifyList = res.data[0]
      var srcList = classifyList.filter(item => {
        return item.level == 2 && item.status != 0
      })

      classifyList.forEach((item, index) => {
        if (item.status == 0) {
          return
        }
        if (item.level == 3) {
          var secInfo = srcList.find(vl => {
            return vl.classCode == item.classParentCode
          }) || {}
          Object.assign(item, {
            firClassCode: secInfo.classParentCode || '',
            firClassId: secInfo.classParentId || '',
            firName: secInfo.classParentName || '',
            secClassCode: secInfo.classCode,
            secClassId: secInfo.classId,
            secName: secInfo.className,
            thrClassCode: item.classCode,
            thrClassId: item.classId,
            thrName: item.className,
            goodsClassCode: item.classCode
          })
        } else if (item.level == 2) {
          Object.assign(item, {
            firClassCode: item.classParentCode || '',
            firClassId: item.classParentId || '',
            firName: item.classParentName || '',
            secClassCode: item.classCode,
            secClassId: item.classId,
            secName: item.className,
            goodsClassCode: item.classCode
          })
        } else if (item.level == 1) {
          Object.assign(item, {
            firClassCode: item.classCode,
            firClassId: item.classId,
            firName: item.className,
            goodsClassCode: item.classCode
          })
        }

      })
      // console.log(classifyList.filter(item => {
      //   return item.level == 3 && item.status != 0
      // }))
      state.newClassifyList = classifyList;
    }
    ,

    //将分类banner图添加到变量classifImageList
    QUERY_CLASSIFY_BANNER(state, res) {
      var data = res.data[0];
      var obj = {};
      for (var key in data) {
        let imageObj = data[key].find(item => {
          return item.relPosition == 'IMAGE';
        });
        obj[key] = {
          image: imageObj ? imageObj.publicityPicture : '',
        };
      }
      state.classifyImageList = obj;
    },

    // 将当前页面的index传给activeIndex
    CHANGE_CLASSIFY_INDEX(state, index) {
      state.classifyIndex = parseInt(index);
    },

    //获取购物车的数据
    QUERY_CART(state, data) {
      state.cartArray = data;
      var storeCode = localStorage.getItem('storeCode');
      var activeCart = state.cartArray.find(item => {
        return storeCode == parseInt(item.storeCode);
      });
      if (activeCart) {
        state.activeCartList = activeCart.shoppingCartLists;
      } else {
        state.activeCartList = [];
      }
    },

    QUERY_ACTIVE_LIST(state) {
      var storeCode = localStorage.getItem('storeCode');
      var cartArray = state.cartArray || []
      var activeCart = cartArray.find(item => {
        return storeCode == parseInt(item.storeCode);
      });
      if (activeCart) {
        state.activeCartList = activeCart.shoppingCartLists;
      } else {
        state.activeCartList = [];
      }
    },

    // 购物车列表中 更新数据
    UPDATA_CART(state, data) {
      data.data.map(newData => {
        var goodsId = newData.goodsId;
        var isInCheckedCartLis;
        var oldDataIndex = state.activeCartList.findIndex(item => {
          return item.goodsId == goodsId;
        });
        if (oldDataIndex !== -1) {
          var oldData = state.activeCartList[oldDataIndex];
          oldData.goodsNum = newData.goodsNum || oldData.goodsNum;
          oldData.serve = newData.serve;
          oldData.preorder = newData.preorder;
          state.activeCartList.splice(oldDataIndex, 1, oldData);
        } else {
          state.activeCartList.push(newData);
        }

        if (/\/cart$/gi.test(window.location.hash)) {
          return;
        }
        isInCheckedCartLis = state.checkedCartList.find(item => {
          return item.goodsId == goodsId;
        });
        if (!isInCheckedCartLis) {
          state.checkedCartList.push(newData);
        }
      });
    },
    //
    ADD_CART_FROM_LOCAL(state, data) {
      var activeCartList = state.activeCartList || [];

      for (var list of data) {
        var goodsId = list.goodsId;

        var oledDataIndex = activeCartList.findIndex(item => {
          return item.goodsId == goodsId;
        });
        if (oledDataIndex == -1) {
          activeCartList.push(list);
        } else {
          var number = activeCartList[oledDataIndex].goodsNum;
          list.goodsNum = list.goodsNum + number;
          activeCartList.splice(oledDataIndex, 1, list);
        }
      }

      state.activeCartList = activeCartList;

      saveLocal(activeCartList);
    },

    // 从本地 购物车列表中更新数据
    UPDATA_CART_FROM_LOCAL(state, data) {
      var activeCartList = state.activeCartList || [];

      for (var list of data) {
        var goodsId = list.goodsId;

        var oledDataIndex = activeCartList.findIndex(item => {
          return item.goodsId == goodsId;
        });
        if (oledDataIndex == -1) {
          activeCartList.push(list);
        } else {
          activeCartList.splice(oledDataIndex, 1, list);
        }
      }

      state.activeCartList = activeCartList;

      saveLocal(activeCartList);
    },

    CHANGE_ALL_CHECKED(state, data) {
      state.activeCartList.map((item, index) => {
        item.preorder = data;
        state.activeCartList.splice(index, 1, item);
      });
    },

    CHANGE_CHECKED(state, data) {
      var goodsId = data.goodsId;
      var findIndex = state.activeCartList.findIndex(item => {
        return item.goodsId == goodsId;
      });
      if (findIndex != -1) {
        var item = state.activeCartList[findIndex];
        item.preorder = data.isChecked;
        state.activeCartList.splice(findIndex, 1, item);
      }
    },

    // 从购物车列表中删除
    DELE_CART(state, data) {
      console.log(data, ',,,,')
      var cartList = state.activeCartList;
      data.map(item => {
        for (var i = 0; cartList.length; i++) {
          if (cartList[i].rid == item.rid) {
            cartList.splice(i, 1);
            break;
          }
        }
      });
      state.activeCartList = cartList;
    },

    DELE_CART_FROM_LOCAL(state, data) {
      var cartList = state.activeCartList;
      data.map(item => {
        for (var i = 0; cartList.length; i++) {
          if (cartList[i].goodsId == item.goodsId) {
            cartList.splice(i, 1);
            break;
          }
        }
      });
      saveLocal(cartList);
    },

    CHANGE_CHECKED_CART_LIST(state, data) {
      state.checkedCartList = data;
    },
    //添加购物车动画
    ADD_CART_ANIMATE(state, num = 1) {
      state.cartAddNum = num;
      state.cartanimateArray.push(state.cartanimateNumber++);
      setTimeout(() => {
        state.cartanimateArray.shift();
      }, 600);
    },

    SET_CART_ICON(state, data) {
      state.cartIcon = data;
    },
    CHANGE_PAGE_POS_Y(state, data) {
      state.pagePosY = data;
    },
    CHANGE_PAGE_NUM(state, data) {
      state.pageNum = data;
    },

    SET_RETURN_POS(state, data) {
      if (!data) {
        return;
      }
      if (state.returnPos[data]) {
        state.returnPos[data].returnPosy = state.pagePosY;
      } else {
        state.returnPos[data] = {returnPosy: state.pagePosY};
      }
    },

    SET_IS_RETURN(state, data) {
      state.isReturn = data;
    },

    CHANGE_DISCOUNT_MONEY(state, data) {
      state.discountMoney = data || 0;
    },

    CHANGE_BAG_LIST(state, data) {
      state.bagList = data || [];
    },

    //线下商城专用
    SET_OFF_LINE_ACTIVE_DATA(state, data) {
      data.sort(function (a, b) {
        return a.rid < b.rid;
      });

      state.offLineAcitveData = data;
    },

    SET_OFF_LINE_SELECT_DATA(state, data) {
      state.offLineSelectData = data;
    },

    OFF_LINE_CHANGE_ALL_CHECKED(state, data) {
      state.offLineAcitveData.map((item, index) => {
        item.preorder = data;
        state.offLineAcitveData.splice(index, 1, item);
      });
    },

    CLEAR_OFF_LINE_DETAIL(state) {
      state.buyMorePrice = 0;
      state.aftrerDiscountMoney = 0;
      state.totalWorkingFee = 0;
      state.discountMoney = 0;
    },

    // 改变已优惠价格 和 优惠后的价格
    INIT_PRICE(state, data) {
      state.aftrerDiscountMoney = data.aftrerDiscountMoney;
      state.discountMoney = data.discountMoney;
      state.totalWorkingFee = data.totalWorkingFee;
    },

    ADD_PROCESS_LIST_DATA(state, data) {
      state.processListData = Object.assign({}, state.processListData, data)
    },

    // 改变已选择的满赠 阶梯加赠
    CHANGE_SELECT_BUY_MORE_LIST: (state, data) => { 
      var selectGiftList = state.selectGiftList;
      var promId = data.promId;
      var goodsCode = data.goodsCode
      var selecIndex = selectGiftList.findIndex(item => {
        return promId == item.promId && goodsCode == item.goodsCode
      });
      if (selecIndex != -1) {
        selectGiftList.splice(selecIndex, 1, data);
      } else {
        selectGiftList.push(data);
      }
      state.selectGiftList = selectGiftList;
    },

    //替换已选择的满赠 赠品列表
    SPLICE_SELECT_BUY_MORE_LIST: (state, data) => {
      var selectGiftList = state.selectGiftList;
      var promId = data.promId;
      var goodsCode = data.goodsCode;
      var selecIndex = selectGiftList.findIndex(item => {
        return promId == item.promId && item.goodsCode == goodsCode
      });
      console.log('selecIndex', selecIndex, goodsCode, promId)
      if (selecIndex != -1) {
        selectGiftList.splice(selecIndex, 1);
      }
      state.selectGiftList = selectGiftList;
    },

    // 改变已选择的返利 赠品
    CHANGE_SELECT_LADDER_LIST: (state, data) => {
      var selectLadderList = state.selectLadderList;
      var promId = data.promId;
      var goodsCode = data.goodsCode;
      var selecIndex = selectLadderList.findIndex(item => {
        return promId == item.promId && item.goodsCode == goodsCode;
      });
      if (selecIndex != -1) {
        selectLadderList.splice(selecIndex, 1, data);
      } else {
        selectLadderList.push(data);
      }
      state.selectLadderList = selectLadderList;
    },

    //替换已选择的返利加赠列表
    SPLICE_SELECT_LADDER_LIST: (state, data) => {
      var selectLadderList = state.selectLadderList;
      var promId = data;

      var selecIndex = selectLadderList.findIndex(item => {
        return promId == item.promId;
      });
      if (selecIndex != -1) {
        selectLadderList.splice(selecIndex, 1);
      }
      state.selectLadderList = selectLadderList;
    },

    CHANGE_BUY_MORE_LIST(state, data) {
      var buyMoreData = state.buyMoreData;
      var promId = data.promId;
      var selecIndex = buyMoreData.findIndex(item => {
        return promId == item.promId;
      });
      if (selecIndex != -1) {
        // buyMoreData[selecIndex].selectNum = data.selectNum
        buyMoreData.splice(selecIndex, 1, data);
      } else {
        buyMoreData.push(data);
      }
      state.buyMoreData = buyMoreData;
    },

    INIT_PRODVO_LIST(state, data) {
      var eachEnougts = [];
      var multisteps = [];
      var allLadderList;
      var allMoreBuy;
      var obj = {};
      var objBuyMore = {};
      var arrayGift = [];
      for (var list of data) {
        if (!list.selected) {
          continue
        }
        var goodsCode = list.goodsCode;
        var promotionalVoList = list.promotionalVoList || [];
        var promotionalVoListOK = promotionalVoList.filter(item => {
          return item.beUsed == 2;
        });

        {
          var leaderList = promotionalVoListOK.filter(item => {
            return item.saleType == 'rebate';
          });

          var tt = leaderList.map(item => {
            var promId = item.promId;
            var promCode = item.promCode;
            if (!obj[promId]) {
              obj[promId] = {
                goodsList: [goodsCode],
                promCode,
              };
            } else {
              obj[promId].goodsList.push(goodsCode);
            }
          });
        }

        {
          var giftList = promotionalVoListOK.filter(item => {
            return item.saleType == 'rebate' && (item.prefWay == 2 || item.prefWay == 1);
          });

          giftList.map(item => {
            var promId = item.promId;
            var promCode = item.promCode;
            if (!objBuyMore[promId]) {
              objBuyMore[promId] = {
                goodsList: [goodsCode],
                promCode,
              };
            } else {
              objBuyMore[promId].goodsList.push(goodsCode);
            }
          });
        }

        {
          promotionalVoListOK.map(item => {

            if (item.saleType == 'buyPresent' && item.prefWay == 3) {

              if (item.prefRange == 1) {
                arrayGift.push({
                  goodsCode: goodsCode,
                  goodsCodeList: '',
                  promId: item.promId,
                  promCode: item.promCode,
                  promotLadderVOList: item.promotLadderVOList,
                });
                console.log(item.prefRange, 'fffff')
              } else {
                var returnIndex = arrayGift.findIndex((val) => {
                  return val.promId == item.promId
                })
                if (returnIndex == -1) {
                  arrayGift.push({
                    goodsCode: '',
                    goodsCodeList: [goodsCode],
                    promId: item.promId,
                    promCode: item.promCode,
                    promotLadderVOList: item.promotLadderVOList,
                  });
                } else {
                  arrayGift[returnIndex].goodsCodeList.push(goodsCode)
                }
              }
            }
          });
        }
      }
      state.allMoreBuy = objBuyMore;
      state.allLadderList = obj;
      state.allGiftList = arrayGift;
    },

    changeCheckedCartList(state, data) {
      state.checkedCartList = data;
      state.selectLadderList = [] //阶梯加价增
      state.selectGiftList = [] // 阶梯赠品
      state.statebuyMoreData = []
    },
  },
};
